#include<iostream>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>



int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"Usage:"<<argv[0]<<"filename"<<std::endl;
        return 1;
    }
    //1.打开目标文件mmap需要你自己先打开文件
    std::string filename=argv[1];
    int fd=open(filename.c_str(),O_RDONLY);
    if(fd<0)
    {
        std::cout<<"Failed to open the file"<<std::endl;
        return 2;
    }
    //2.获取文件真实大小
    struct stat st;
    fstat(fd,&st);
   
    //3.文件映射
    char* shmaddr=(char*)mmap(NULL,st.st_size,PROT_READ,MAP_SHARED,fd,0);
    if(shmaddr==MAP_FAILED)
    {
        std::cout<<"Failed to mmap"<<std::endl;
        return 3;
    }
    //4.进行文件操作
    std::cout<<shmaddr<<std::endl;
    //5.取消映射
    if(munmap(shmaddr,st.st_size)==-1)
    {
        std::cout<<"Failed to munmap"<<std::endl;
        return 5;
    }
    close(fd);
    return 0;
}